package com.onesports.intelligent.k12.polarlight.security;


import com.onesports.intelligent.k12.polarlight.config.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.IpAddressMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * ip白名单校验器
 *
 * @author aj
 */
@Slf4j
public class ClientWhiteListSecurity {

    private final ApplicationProperties applicationProperties;

    public ClientWhiteListSecurity(ApplicationProperties applicationProperties) {
        this.applicationProperties = applicationProperties;
    }

    public boolean innerWhiteListCheck(Authentication authentication, HttpServletRequest request) {
//        Set<String> ips = applicationProperties.getSecurity().getAuthentication().getInner().getIpAddresses();
//        for (String ip : ips) {
//            log.debug("请求ip地址:{}", request.getRemoteAddr());
//            if (StringUtils.isBlank(ip)) {
//                return false;
//            } else if (hasIpAddress(request, ip)) {
//                return true;
//            } else {
//                log.warn("请求ip地址:{}", request.getRemoteAddr());
//            }
//        }
        return false;
    }

    public boolean openWhiteListCheck(Authentication authentication, HttpServletRequest request) {
        DomainUserDetails userDetails = (DomainUserDetails) authentication.getDetails();
        if (userDetails == null) {
            return false;
        }
//        for (String ip : ips) {
//            if (StringUtils.isBlank(ip)) {
//                return false;
//            } else if (hasIpAddress(request, ip)) {
//                return true;
//            }
//        }
        return false;
    }

    private boolean hasIpAddress(HttpServletRequest request, String ipAddress) {
        IpAddressMatcher matcher = new IpAddressMatcher(ipAddress);
        return matcher.matches(request);
    }
}
